<template>
  <div class="lighting-monitor">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>灯光设备管理</h2>
      <div class="header-actions">
        <el-button type="primary" icon="el-icon-refresh" @click="refreshData">刷新数据</el-button>
        <el-button type="success" icon="el-icon-setting" @click="showSettings">参数配置</el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <el-row :gutter="20">
        <!-- 左侧：运行日志 -->
        <el-col :span="8">
          <div class="log-section">
            <div class="section-header">
              <i class="el-icon-document"></i>
              <!-- 动态显示日志总数 -->
              <span>运行日志（共 {{ logTotal }} 条）</span>
              <div class="header-controls">
                <el-button type="text" size="mini" @click="clearLogs">清空日志</el-button>
              </div>
            </div>
            <div class="log-container" v-loading="logLoading">
              <div v-if="logs.length === 0 && !logLoading" class="no-data">
                暂无日志数据
              </div>
              <!-- 使用后端日志 id 作为 key，提升渲染稳定性 -->
              <div v-for="(log, index) in logs" :key="log.id || index" class="log-item" :class="getLogClass(log.type)">
                <span class="log-time">{{ log.time }}</span>
                <!-- 标签类型与中文文案由 logType 映射得到 -->
                <el-tag :type="getLogTagType(log.type)" size="mini">{{ getLogTypeText(log.type) }}</el-tag>
                <span class="log-device">{{ log.deviceName }}</span>
                <span class="log-message">{{ log.content }}</span>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 右侧：设备卡片区域 -->
        <el-col :span="16">
          <div class="device-section">
            <div class="section-header">
              <i class="el-icon-monitor"></i>
              <span>设备控制</span>
            </div>
            <div class="device-cards">
              <el-row :gutter="20">
                <el-col :span="12" v-for="device in devices" :key="device.id">
                  <div class="device-card">
                    <!-- 设备名称 -->
                    <div class="device-name">{{ device.name }}</div>

                    <!-- 设备状态 -->
                    <div class="device-control">
                      <div class="control-item">
                        <span class="control-label">设备状态</span>
                        <el-switch
                          v-model="device.status"
                          active-color="#13ce66"
                          inactive-color="#dcdfe6"
                          @change="onDeviceStatusChange(device)"
                        />
                      </div>
                    </div>

                    <!-- 工作模式 -->
                    <div class="device-control">
                      <div class="control-item">
                        <span class="control-label">工作模式</span>
                        <el-radio-group v-model="device.workMode" @change="onWorkModeChange(device)">
                          <el-radio label="timing">定时</el-radio>
                          <el-radio label="manual">手动</el-radio>
                        </el-radio-group>
                      </div>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { getLightingDeviceList, getLightingDeviceLogs, clearLightingDeviceLogs, controlLightingDevice } from "@/api/archives/lighting";

export default {
  name: "LightingMonitor",
  data() {
    return {
      // 运行日志数据
      logs: [],
      // 日志总条数（来自后端 totalSize 或回退为 data.length）
      logTotal: 0,
      // 设备数据
      devices: [],
      // 加载状态
      loading: false,
      logLoading: false
    }
  },
  created() {
    this.getDeviceList();
    this.getLogsList();
  },

  mounted() {
    this.initData()
  },

  methods: {
    // 获取设备列表
    async getDeviceList() {
      this.loading = true;
      try {
        const response = await getLightingDeviceList();
        if (response.code === 200) {
          this.devices = response.data.map(device => ({
            id: device.id,
            name: device.deviceName,
            alias: device.alias,
            ident: device.ident,
            storeId: device.storeId,
            storeCode: device.storeCode,
            storeName: device.storeName,
            termId: device.termId,
            deviceType: device.deviceType,
            deviceTypeCode: device.deviceTypeCode,
            deviceAddrCode: device.deviceAddrCode,
            status: device.opStatus === '1', // '1'表示开启，'0'表示关闭
            workMode: '', // 默认无选中
            // 定时相关字段
            startTimeFirst: device.startTimeFirst || '',
            endTimeFirst: device.endTimeFirst || '',
            weeksFirst: device.weeksFirst || '',
            startTimeSecond: device.startTimeSecond || '',
            endTimeSecond: device.endTimeSecond || '',
            weeksSecond: device.weeksSecond || '',
            startTimeThird: device.startTimeThird || '',
            endTimeThird: device.endTimeThird || '',
            weeksThird: device.weeksThird || ''
          }));
        }
      } catch (error) {
        this.$modal.msgError("获取设备列表失败");
        console.error(error);
      } finally {
        this.loading = false;
      }
    },

    // 获取运行日志（按后端返回结构映射到页面使用的字段）
    async getLogsList() {
      this.logLoading = true;
      try {
        const response = await getLightingDeviceLogs();
        if (response.code === 200) {
          // 后端 logType 与前端展示类型映射：1-信息，2-成功，3-警告，4-错误
          const typeMap = { '1': 'info', '2': 'success', '3': 'warning', '4': 'error' };
          const raw = Array.isArray(response.data) ? response.data : [];
          // 将后端日志数据转换为页面展示所需结构
          this.logs = raw.map(item => ({
            id: item.id,
            // 优先使用后端 createTime，否则用 timeStamp 格式化
            time: item.createTime ? item.createTime : this.formatTimestamp(item.timeStamp),
            type: typeMap[item.logType] || 'info',
            deviceName: item.deviceName || '-',
            content: item.deviceOpLog || ''
          }));
          // 保存总条数（totalSize），若缺失则回退为数组长度
          this.logTotal = Number(response.totalSize) || this.logs.length;
        }
      } catch (error) {
        this.$modal.msgError("获取运行日志失败");
        console.error(error);
      } finally {
        this.logLoading = false;
      }
    },

    // 初始化数据
    initData() {
      this.refreshData()
    },

    // 刷新数据
    refreshData() {
      this.getDeviceList();
      this.getLogsList();
    },

    // 清空日志
    async clearLogs() {
      this.$confirm('确认清空所有日志记录？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await clearLightingDeviceLogs();
          if (response.code === 200) {
            this.logs = [];
            this.$message.success('日志已清空');
          } else {
            this.$message.error(response.msg || "日志清空失败");
          }
        } catch (error) {
          this.$message.error("日志清空失败");
          console.error(error);
        }
      }).catch(() => {
        this.$message.info('已取消操作')
      })
    },

    // 获取日志样式类
    getLogClass(type) {
      return `log-${type}`
    },

    // 获取日志标签类型
    getLogTagType(type) {
      const typeMap = {
        'success': 'success',
        'info': 'info',
        'warning': 'warning',
        'error': 'danger'
      }
      return typeMap[type] || 'info'
    },

    // 获取日志类型中文文案（用于标签显示）
    getLogTypeText(type) {
      const textMap = {
        'success': '成功',
        'info': '信息',
        'warning': '警告',
        'error': '错误'
      }
      return textMap[type] || '信息'
    },

    // 将时间戳格式化为 "YYYY-MM-DD HH:mm:ss"
    formatTimestamp(ts) {
      if (!ts) return '';
      const d = new Date(Number(ts));
      const pad = n => (n < 10 ? '0' + n : '' + n);
      return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
    },

    // 设备状态变化
    async onDeviceStatusChange(device) {
      try {
        const controlData = {
          id: device.id,
          opStatus: device.status ? '1' : '0'
        };

        const response = await controlLightingDevice(controlData);
        if (response.code === 200) {
          const status = device.status ? '开启' : '关闭'
          this.$message.success(`${device.name} 已${status}`);
          // 添加日志记录
          this.addLog('info', device.name, `设备状态切换为${status}`);
          // 刷新设备列表
          this.getDeviceList();
        } else {
          // 如果失败，恢复原状态
          device.status = !device.status;
          this.$message.error(response.msg || "设备控制失败");
        }
      } catch (error) {
        // 如果失败，恢复原状态
        device.status = !device.status;
        this.$message.error("设备控制失败");
        console.error(error);
      }
    },

    // 工作模式变化
    onWorkModeChange(device, mode) {
      device.workMode = mode;
      const modeText = mode === 'timing' ? '定时' : '手动';
      this.$message.success(`${device.name} 工作模式已切换为${modeText}`);

      // 添加日志记录
      this.addLog('info', device.name, `工作模式切换为${modeText}`);
    },

    // 参数配置
    handleConfig() {
      this.$message.info('参数配置功能开发中...');
    },

    // 添加日志记录
    addLog(type, deviceName, content) {
      const now = new Date();
      const time = now.toTimeString().split(' ')[0];
      this.logs.unshift({
        time,
        type,
        deviceName,
        content
      });

      // 限制日志数量，最多保留100条
      if (this.logs.length > 100) {
        this.logs = this.logs.slice(0, 100);
      }
    }
  }
}
</script>

<style scoped>
.lighting-monitor {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 页面标题 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.page-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

/* 主要内容区域 */
.main-content {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

/* 区域标题 */
.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #e6e6e6;
}

.section-header i {
  font-size: 18px;
  color: #409eff;
  margin-right: 8px;
}

.section-header span {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  flex: 1;
}

.header-controls {
  display: flex;
  gap: 10px;
}

/* 日志区域 */
.log-section {
  height: 600px;
  display: flex;
  flex-direction: column;
}

.log-container {
  flex: 1;
  overflow-y: auto;
  border: 1px solid #e6e6e6;
  border-radius: 6px;
  padding: 10px;
  background: #fafafa;
}

.no-data {
  text-align: center;
  color: #999;
  padding: 40px 0;
}

.log-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  font-size: 12px;
}

.log-item:last-child {
  border-bottom: none;
}

.log-time {
  color: #666;
  margin-right: 10px;
  min-width: 60px;
}

.log-device {
  color: #409eff;
  margin: 0 10px;
  min-width: 100px;
}

.log-message {
  color: #333;
  flex: 1;
}

.log-success {
  background-color: #f0f9ff;
}

.log-warning {
  background-color: #fdf6ec;
}

.log-error {
  background-color: #fef0f0;
}

.log-info {
  background-color: #f4f4f5;
}

/* 设备区域 */
.device-section {
  height: 600px;
  display: flex;
  flex-direction: column;
}

.device-cards {
  flex: 1;
}

/* 设备卡片 */
.device-card {
  background: #fff;
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  margin-bottom: 20px;
}

.device-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.device-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
  text-align: center;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.device-control {
  margin-bottom: 20px;
}

.device-control:last-child {
  margin-bottom: 0;
}

.control-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.control-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

/* 开关样式 */
.el-switch {
  transform: scale(1.2);
}

/* 单选按钮组样式 */
.el-radio-group {
  display: flex;
  gap: 20px;
}

.el-radio {
  margin-right: 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .device-cards .el-col {
    margin-bottom: 20px;
  }
}

@media (max-width: 768px) {
  .main-content .el-row {
    flex-direction: column;
  }

  .log-section,
  .device-section {
    height: auto;
    min-height: 400px;
  }

  .page-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
}
</style>
